/*
 * @lc app=leetcode.cn id=114 lang=javascript
 *
 * [114] 二叉树展开为链表
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {void} Do not return anything, modify root in-place instead.
 */
var flatten = function (root) {
  const stack = [];

  const preOrderHelper = (root) => {
    if (!root) return;
    stack.push(root);
    if (root.left) preOrderHelper(root.left);
    if (root.right) preOrderHelper(root.right);
  };

  preOrderHelper(root);

  for (let i = 0; i < stack.length - 1; i++) {
    stack[i].left = null;
    stack[i].right = stack[i + 1];
  }
  return stack[0];
};
// @lc code=end
